package com.rjkj.medicalwaste.ui.setting

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.DialogInterface
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.gson.Gson
import com.inuker.bluetooth.library.utils.BluetoothUtils
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.BlueConnectResult
import com.rjkj.medicalwaste.bean.SettingBean
import com.rjkj.medicalwaste.databinding.FragmentCommonSettingBinding
import com.rjkj.medicalwaste.utils.*
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import java.util.regex.Pattern


class CommonSettingFragment : BaseFragment<FragmentCommonSettingBinding>() {
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentCommonSettingBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }


    @SuppressLint("SetTextI18n")
    override fun onSubscribeUi(binding: FragmentCommonSettingBinding) {
        initTip(userViewModel)
        bluetoothControlViewModel.bluetoothSwitch.observe(viewLifecycleOwner) {
            binding.bluetoothSwitch.isChecked = it
        }
        userViewModel.setting.observe(viewLifecycleOwner) {
            if (it.change) {
                AppPrefsUtils.putString(BaseConstant.SETTING, Gson().toJson(it))
                showTip("设置成功")
                it.change = false
            }
            val urlName = if (it.url.isEmpty()) {
                "服务器选择"
            } else {
                it.url
            }
            binding.serverChange.text = urlName
            binding.tvOnly.text = "唯一号：${it.id}"
            binding.prefabricatedLabel.isChecked = it.prefabricatedLabel
            binding.boxCode.isChecked = it.fixedBoxCode
            binding.review.isChecked = it.review
            binding.btBindHospital.text = "绑定医院:${userViewModel.hospitalName.value}"
            binding.tvVersion.text = ("设备号：" + it.serialNum)
            val info = when (userViewModel.setting.value?.infoMode) {
                0 -> {
                    binding.prefabricatedLabel.isEnabled = true
                    binding.boxCode.isEnabled = true
                    binding.review.isEnabled = true
                    binding.bluetoothSwitch.isEnabled = true
                    binding.btBlueSetting.isEnabled = true
                    binding.btPrintItem.visibility = View.VISIBLE
                    binding.btPrintItemLine.visibility = View.VISIBLE
                    "PDA"
                }
                2 -> {
                    binding.prefabricatedLabel.isEnabled = true
                    binding.boxCode.isEnabled = false
                    binding.review.isEnabled = false
                    binding.bluetoothSwitch.isEnabled = true
                    binding.btBlueSetting.isEnabled = true
                    binding.btPrintItem.visibility = View.VISIBLE
                    binding.btPrintItemLine.visibility = View.VISIBLE
                    "贵州"
                }
                else -> {
                    binding.prefabricatedLabel.isEnabled = false
                    binding.boxCode.isEnabled = false
                    binding.review.isEnabled = false
                    binding.bluetoothSwitch.isEnabled = false
                    binding.btBlueSetting.isEnabled = false
                    binding.btPrintItem.visibility = View.GONE
                    binding.btPrintItemLine.visibility = View.GONE
                    "手机"
                }
            }
            binding.btInfoMode.text = "信息采集模式:${info}"
            if (userViewModel.hospitalName.value.isNullOrEmpty()) {
                binding.btGetHospital.isEnabled = false
                binding.btGetHospital.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.grey_text
                    )
                )
            } else {
                binding.btGetHospital.isEnabled = true
                binding.btGetHospital.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.black
                    )
                )
            }

        }

        binding.btPrintItem.setOnClickListener {
            findNavController().navigate(R.id.action_commonSettingFragment_to_printItemFragment)
        }
        binding.btBlueSetting.setOnClickListener {
            findNavController().navigate(R.id.action_commonSettingFragment_to_bluetoothListFragment)
        }
//        binding.btBleSetting.setOnClickListener {
//            findNavController().navigate(R.id.action_commonSettingFragment_to_bleListFragment)
//        }
        val value = userViewModel.setting.value!!
        binding.btInfoMode.setOnClickListener {
            val infoModeItems = arrayOf("PDA模式", "手机模式","贵州模式")
            AlertDialog.Builder(requireContext()).apply {
                setSingleChoiceItems(
                    infoModeItems,
                    userViewModel.setting.value?.infoMode ?: 0
                ) { _: DialogInterface, i: Int ->
                    value.infoMode = i
                    if (i == 1) {
                        value.prefabricatedLabel = true
                        value.fixedBoxCode = false
                        value.review = false
                    }else if(i == 2){
                        value.prefabricatedLabel = true
                        value.fixedBoxCode = false
                        value.review = false
                    }
                    value.change = true
                    userViewModel.setting.value = value
                }
                setNegativeButton("关闭") { _: DialogInterface, _: Int ->
                }

            }.show()

        }
        binding.serverChange.setOnClickListener {
            userViewModel.findIPAndPort()
        }
        binding.prefabricatedLabel.setOnCheckedChangeListener { _: CompoundButton, b: Boolean ->
            value.prefabricatedLabel = b
            value.change = true
            userViewModel.setting.value = value
        }
        binding.boxCode.setOnCheckedChangeListener { _: CompoundButton, b: Boolean ->
            value.fixedBoxCode = b
            value.change = true
            userViewModel.setting.value = value
        }
        binding.review.setOnCheckedChangeListener { _: CompoundButton, b: Boolean ->
            value.review = b
            value.change = true
            userViewModel.setting.value = value
        }
        binding.btBindHospital.setOnClickListener {
            findNavController().navigate(R.id.action_commonSettingFragment_to_searchHospitalFragment)
        }
        binding.bluetoothSwitch.setOnCheckedChangeListener { _: CompoundButton, b: Boolean ->
            val bt = BlueManager.instance.blue
            if (b) {
                val mac = AppPrefsUtils.getString(BaseConstant.BLUETOOTH_MAC)
                val mDevice: BluetoothDevice = BluetoothUtils.getRemoteDevice(mac)
                    ?: return@setOnCheckedChangeListener
                bluetoothControlViewModel.bluetoothTry.value = BlueConnectResult(mac,mDevice.type)
            } else {
                bt.disconnect()
            }
        }
        binding.btGetHospital.setOnClickListener {
            AlertDialog.Builder(requireContext())
                .setTitle("是否重新获取${userViewModel.hospitalName.value}数据")
                .setNegativeButton("取消") { _: DialogInterface, _: Int ->
                }
                .setPositiveButton("确定") { _: DialogInterface, _: Int ->
                    userViewModel.getAllUserData()
                }
                .show()

        }
        binding.imBack.setOnClickListener {
            requireActivity().onBackPressed()
        }
        binding.tvVersion.setOnClickListener {
            if (PhoneHelper.isDebug()) {
                setIMEI(value)
            }
        }
        binding.tvOnly.setOnClickListener {
//            val serial = userViewModel.getSerial()
//            if(serial.isNotEmpty()&& Pattern.compile("^\\d{15}\$").matcher(serial).matches()){
//                setOnlyCode()
//            }else{
//                showTip("请先设置设备号")
//                setIMEI(value)
//            }
            setOnlyCode()
        }
    }

    private fun setOnlyCode() {
        if (!AppPrefsUtils.getBoolean(BaseConstant.SET_UNIQUE, false)) {
            val editText = EditText(requireContext())
            editText.inputType = InputType.TYPE_CLASS_NUMBER
            val inputDialog = AlertDialog.Builder(requireContext())
            inputDialog.setTitle("输入唯一号").setView(editText)
            inputDialog.setPositiveButton(
                "确定"
            ) { _, _ ->
                userViewModel.setSerialNum(
                    userViewModel.getSerial(),
                    editText.text.toString(),
                    PhoneHelper.getInstance(requireContext()).subscriberId
                )
            }.show()
        } else {
            showTip("您已设置过唯一号")
        }
    }

    private fun setIMEI(value: SettingBean) {
        if (!AppPrefsUtils.getBoolean(BaseConstant.SET_DEVICE_IMEI, false)) {
            val editText = EditText(requireContext())
            editText.inputType = InputType.TYPE_CLASS_NUMBER
            editText.filters = arrayOf(InputFilter.LengthFilter(15))
            val inputDialog = AlertDialog.Builder(requireContext())
            inputDialog.setTitle("输入设备号（仅一次）").setView(editText)
            inputDialog.setPositiveButton(
                "确定"
            ) { _, _ ->
                val toString = editText.text.toString()
                if (toString.length == 15) {
                    value.serialNum = toString
                    value.change = true
                    userViewModel.setting.value = value
                    AppPrefsUtils.putBoolean(BaseConstant.SET_DEVICE_IMEI, true)
                }
            }.show()
        } else {
            showTip("您已设置过设备号")
        }
    }


}